package com.example.jvm.whenload;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

/**
 * 类加载的基本逻辑是
 * 获取二进制字节流，转化结构存储到方法区，生成代表这个类的Class对象。
 *
 * <p>
 *     不同类加载器会影响类的比较，
 *     {@link Class#isAssignableFrom(Class)}
 *     {@link Class#equals(Object)}
 *     {@link Class#isInstance(Object)}
 *     以及instanceof
 * </p>
 */
public class MyClassLoader extends ClassLoader {

    /**
     * <p>
     *     双亲委派模型以及同步机制已在：
     *     {@link ClassLoader#loadClass(String)}
     *     实现，这里不需要做处理
     * </p>
     * @param name
     *          The <a href="#binary-name">binary name</a> of the class
     *
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] bytes;
        String classFileName = "C:\\Users\\mengtain\\IdeaProjects\\study-spring\\jvm\\file\\" + name;
        try (InputStream inputStream = Files.newInputStream(Path.of(classFileName), StandardOpenOption.READ)){
            bytes = inputStream.readAllBytes();
        } catch (IOException ignored) {
            throw new ClassNotFoundException("找不到类");
        }
        return defineClass("com.example.jvm.whenload.MyBinaryTestClass", bytes, 0, bytes.length);
    }

}
